/**
 * TSC 244 pro 打印机驱动
 * 作者：郭强
 * 时间：2024-06-29
 */

export default {
    targetVue: null,
    printer: [],
    fromUint8Array(u8a) {
        // var _hasbtoa = typeof btoa === 'function';

        var _fromCC = String.fromCharCode.bind(String);
        var maxargs = 0x1000;
        var strs = [];
        for (var i = 0, l = u8a.length; i < l; i += maxargs) {
            strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));
        }
        return btoa(strs.join(''));
        
    },
    /**
     * 安装驱动到vue组件中
     */
    setup(vueThis) {
        this.targetVue = vueThis;
    },
    /**
     * 取得打印机列表
     */
    getPrinterList(){
        var obj = {"usb_list": []};
        this.printer = [];
		this.sendcmd(obj);
    },
    resetprint(config){
        const u8 = new Uint8Array(2);
		u8[0] = 13;
		u8[1] = 10;
        let functions_inorder=[];
        functions_inorder.push({"openport_usb" : this.printer.path});
        functions_inorder.push({"sendUint8Array" : this.fromUint8Array(u8)});
        functions_inorder.push({"clearbuffer" : ""});
        //标签宽度(单位mm)
        let width_mm = config.width_mm;
        //标签高度(单位mm)
        let height_mm = config.height_mm;
        //打印速度
        let speed = config.speed;
        //打印浓度
        let density = config.density;
        //標籤種類["0":GAP, "1":BLINE]
        let sensor = config.sensor;;
        //间隙高度(单位mm)
        let gap_height = config.gap_height;
        //间隙偏移(单位mm)
        let gap_offset = config.gap_offset;

        functions_inorder.push({"setup" : width_mm + "," + height_mm + "," +speed + "," +density + "," +sensor + "," +gap_height + "," +gap_offset});
        //条码x轴座标(单位dot)
        let x = config.x;
        //条码y轴座标(单位dot)
        let y = config.y;
        //条码类型["128", "128M", "EAN128", "25", "25C", "39", "39C", "93", "EAN13", "EAN13+2", "EAN13+5", "EAN8", "EAN8+2", "EAN8+5", "CODA", "POST", "UPCA", "UPCA+2", "UPCA+5", "UPCE", "UPCE+2", "UPCE+5", "CPOST", "MSI", "MSIC", "PLESSEY", "ITF14", "EAN14", "11", "TELEPEN", "TELEPENN", "PLANET", "CODE49", "DPI", "DPL"]
        let type = config.type;
        //条码高度
        let height = config.height;
        //条码可读性["0":无, "1":置左, "2":置中, "3":置右]
        let readable = config.readable;
        //条码旋转["0":无, "90":90度, "180":180度, "270":270度]
        let rotation = config.rotation;
        //条码窄元件宽度[详见TSPL手册BARCODE条目]
        let narrow = config.narrow;
        //条码宽元件宽度[详见TSPL手册BARCODE条目]
        let wide = config.wide;
        functions_inorder.push({"barcode" : x + "," + y + ",\"" + type + "\"," + height + "," + readable + "," + rotation + "," + narrow + "," + wide + ",\"123456\"" });
        functions_inorder.push({"sendcommand_crlf" : "PUTPCX 800,150,\"UL.PCX\""});
        let sets = 1;
        let copies = 1;
        functions_inorder.push({"printlabel" : sets + "," + copies});
        functions_inorder.push({"closeport" : ""});

        let obj = {functions_inorder: functions_inorder};
        this.sendcmd(obj);
    },
    printCode(code, config, listWord) {
        const u8 = new Uint8Array(2);
        u8[0] = 13;
        u8[1] = 10;
        let functions_inorder=[];
        functions_inorder.push({"openport_usb" : this.printer.path});
        functions_inorder.push({"sendUint8Array" : this.fromUint8Array(u8)});
        functions_inorder.push({"clearbuffer" : ""});
        //标签宽度(单位mm)
        let width_mm = config.width_mm;
        //标签高度(单位mm)
        let height_mm = config.height_mm;
        //打印速度
        let speed = config.speed;
        //打印浓度
        let density = config.density;
        //標籤種類["0":GAP, "1":BLINE]
        let sensor = config.sensor;;
        //间隙高度(单位mm)
        let gap_height = config.gap_height;
        //间隙偏移(单位mm)
        let gap_offset = config.gap_offset;

        functions_inorder.push({"setup" : width_mm + "," + height_mm + "," +speed + "," +density + "," +sensor + "," +gap_height + "," +gap_offset});
        //条码x轴座标(单位dot)
        let x = config.x;
        //条码y轴座标(单位dot)
        let y = config.y;
        //条码类型["128", "128M", "EAN128", "25", "25C", "39", "39C", "93", "EAN13", "EAN13+2", "EAN13+5", "EAN8", "EAN8+2", "EAN8+5", "CODA", "POST", "UPCA", "UPCA+2", "UPCA+5", "UPCE", "UPCE+2", "UPCE+5", "CPOST", "MSI", "MSIC", "PLESSEY", "ITF14", "EAN14", "11", "TELEPEN", "TELEPENN", "PLANET", "CODE49", "DPI", "DPL"]
        let type = config.type;
        //条码高度
        let height = config.height;
        //条码可读性["0":无, "1":置左, "2":置中, "3":置右]
        let readable = config.readable;
        //条码旋转["0":无, "90":90度, "180":180度, "270":270度]
        let rotation = config.rotation;
        //条码窄元件宽度[详见TSPL手册BARCODE条目]
        let narrow = config.narrow;
        //条码宽元件宽度[详见TSPL手册BARCODE条目]
        let wide = config.wide;
        functions_inorder.push({"barcode" : x + "," + y + ",\"" + type + "\"," + height + "," + readable + "," + rotation + "," + narrow + "," + wide + ",\"" + code + "\"" });

        let font_x = 480;
        let font_y = 330;
        // let fonttype = "2";
        // let font_rotation = "90";
        // let xmul = "1";
        // let ymul = "1";
        // let text = "\"orderNO: 1203123123\"";
        // functions_inorder.push({"printerfont" : font_x + "," + font_y + ",\"" + fonttype + "\"," + font_rotation + "," + xmul + "," + ymul + "," + text});

        // font_x = 430;
        let fontheight = "30";
        let fontstyle = "2";
        let fontunderline = "0";
        let szFaceName = "Arial";
        let wordRotation = 270; 
        for (let i in listWord) {
            let word = listWord[i];
            font_x = 490 - (i * 35);
            functions_inorder.push({"windowsfont" : font_x + "," + font_y + "," +fontheight + "," + wordRotation + "," + fontstyle + "," +fontunderline + "," + szFaceName + "," + word});
        }
        
        // functions_inorder.push({"sendcommand_crlf" : "PUTPCX 800,150,\"UL.PCX\""});
        let sets = 1;
        let copies = 1;
        functions_inorder.push({"printlabel" : sets + "," + copies});
        functions_inorder.push({"closeport" : ""});

        let obj = {functions_inorder: functions_inorder};
        this.sendcmd(obj);

        
    },
    printSend(listWord, config) {
        const u8 = new Uint8Array(2);
		u8[0] = 13;
		u8[1] = 10;
        let functions_inorder=[];
        functions_inorder.push({"openport_usb" : this.printer.path});
        functions_inorder.push({"sendUint8Array" : this.fromUint8Array(u8)});
        functions_inorder.push({"clearbuffer" : ""});
        //标签宽度(单位mm)
        let width_mm = config.width_mm;
        //标签高度(单位mm)
        let height_mm = config.height_mm;
        //打印速度
        let speed = config.speed;
        //打印浓度
        let density = config.density;
        //標籤種類["0":GAP, "1":BLINE]
        let sensor = config.sensor;;
        //间隙高度(单位mm)
        let gap_height = config.gap_height;
        //间隙偏移(单位mm)
        let gap_offset = config.gap_offset;

        functions_inorder.push({"setup" : width_mm + "," + height_mm + "," +speed + "," +density + "," +sensor + "," +gap_height + "," +gap_offset});
        //条码x轴座标(单位dot)
        let x = config.x;
        //条码y轴座标(单位dot)
        let y = config.y;
        //条码类型["128", "128M", "EAN128", "25", "25C", "39", "39C", "93", "EAN13", "EAN13+2", "EAN13+5", "EAN8", "EAN8+2", "EAN8+5", "CODA", "POST", "UPCA", "UPCA+2", "UPCA+5", "UPCE", "UPCE+2", "UPCE+5", "CPOST", "MSI", "MSIC", "PLESSEY", "ITF14", "EAN14", "11", "TELEPEN", "TELEPENN", "PLANET", "CODE49", "DPI", "DPL"]
        let type = config.type;
        //条码高度
        let height = config.height;
        //条码可读性["0":无, "1":置左, "2":置中, "3":置右]
        let readable = config.readable;
        //条码旋转["0":无, "90":90度, "180":180度, "270":270度]
        let rotation = config.rotation;
        //条码窄元件宽度[详见TSPL手册BARCODE条目]
        let narrow = config.narrow;
        //条码宽元件宽度[详见TSPL手册BARCODE条目]
        let wide = config.wide;
        // functions_inorder.push({"barcode" : x + "," + y + ",\"" + type + "\"," + height + "," + readable + "," + rotation + "," + narrow + "," + wide + ",\"" + code + "\"" });
        console.log(config);
        for (let pos in listWord) {
            let word = listWord[pos];
            let font_x = 260;
            let font_y = 40 + (pos * 35);
            let fontheight = "30";
            let rotation = "0";
            let fontstyle = "2";
            let fontunderline = "0";
            let szFaceName = "Arial";
            let text = "\"" + word + "\"";
            functions_inorder.push({"windowsfont" : font_x + "," + font_y + "," + fontheight + "," + rotation + "," + fontstyle + "," + fontunderline + "," + szFaceName + "," + text});
            // functions_inorder.push({"printerfont" : font_x + "," + font_y + ",\"" + fonttype + "\"," + font_rotation + "," + xmul + "," + ymul + "," + text});
        }
        console.log(functions_inorder);
        functions_inorder.push({"sendcommand_crlf" : "PUTPCX 800,150,\"UL.PCX\""});
        let sets = 1;
        let copies = 1;
        functions_inorder.push({"printlabel" : sets + "," + copies});
        functions_inorder.push({"closeport" : ""});

        let obj = {functions_inorder: functions_inorder};
        this.sendcmd(obj);
    },
    sendcmd(obj)
	{
        //本地打印服务地址
        var url = "ws://127.0.0.1:8888";
		var websocket = new WebSocket(url);
		websocket.onopen = e => {
            //发送指令
            websocket.send(JSON.stringify(obj));
		};
		websocket.onmessage = (event) => {
			if(event.data == "Finished"){
                //指令执行完毕
				websocket.close();
                this.targetVue.$message.success("打印完成");
            } else {
                //其他事件
				try {
					const obj = JSON.parse(event.data);
					if ('usb_list' in obj) {
                        //打印机列表
                        let listPrinter = [];
                        for(let i=0; i < obj.usb_list.length; i++) {
                            var opt = document.createElement('option');
                            let printer = {
                                path: obj.usb_list[i].USBPath,
                                name: obj.usb_list[i].USBName
                            }
                            listPrinter.push(printer);
                        }
                        this.targetVue.listPrinter = listPrinter;
                        this.printer = listPrinter[0];
					}
					if ('Function_Failed' in obj)
					{
                        //指令执行失败
                        // alert("打印机错误：" + obj.Function_Failed);
                        if (this.targetVue) {
                            this.targetVue.$message.success("打印机错误：");
                        }
					}
					if ('printerstatus' in obj)
					{
                        //打印机状态
                        if (obj.printerstatus.length != 0) {
                            alert("打印机状态：" + obj.printerstatus.join("\r\n"));
                        }
					}
					if ('printername' in obj)
					{
                        //打印机名称
						alert(`打印机名称: ${obj.printername}\r\n`);
					}
					if ('printerserial' in obj)
					{
						alert(`打印机序列号: ${obj.printerserial}\r\n`);
					}
					if ('about' in obj)
					{
						alert(`打印机版本: ${obj.about}\r\n`);
					}
				} catch (e) {
					// alert(`打印机异常`);
                    if (this.targetVue) {
                        this.targetVue.$message.success("打印机错误：");
                    }
				}
			}
		};

		websocket.onclose = function(event) {
			if (event.code != 1000)
			{
				var reason = "";
				if(event.code == 1001)
					reason = "打印机服务未打开";
				else if(event.code == 1002)
					reason = "连接打印服务端协议错误，终止连接";
				else if(event.code == 1003)
					reason = "无法接收的数据类型，正在断开连接";
				else if(event.code == 1004)
					reason = "未知错误";
				else if(event.code == 1005)
					reason = "未知错误";
				else if(event.code == 1006)
				   reason = "连接异常关闭";
				else if(event.code == 1007)
					reason = "无法接收的指令类型，正在断开连接";
				else if(event.code == 1008)
					reason = "指令消息违反安全策略，正在断开连接";
				else if(event.code == 1009)
				   reason = "指令数据太大，无法接收，正在断开连接";
				else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
					reason = "连接错误:" + event.reason;
				else if(event.code == 1011)
					reason = "意异关闭";
				else if(event.code == 1015)
					reason = "无法验证服务器证书";
				else
					reason = "未知错误:"+event.code + " reason=" + reason;
				}
		};

		websocket.onerror = function(error) {
		  alert(`[error] ${error.message}`);
		};
	}
}